<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/1
 * Time: 10:41
 */


class McryptTool{

    private $testPubKeyPath = './testks/pub_key.pem' ;
    private $testPriKeyPath = './testks/pri_key.pem' ;

    private $iv;
    private $key ;

    public function __construct()
    {

    }

    public function encodeRequest($data){

        if (is_array($data)){
            $srcData = json_encode($data) ;
        }else{
            $srcData = $data ;
        }

        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');

        $blockSize = mcrypt_enc_get_block_size($td);

        $ks = 16;

        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td));
        $this->iv = $iv ;

        $key = substr(md5(uniqid()), 0, $ks);
        $this->key = $key;

        mcrypt_generic_init($td, $key, $iv);

        $encrypted = mcrypt_generic($td, $this->pkcs5_pad($srcData, $blockSize));
        $mdata = base64_encode($encrypted);

        $kpath = $this->testPubKeyPath ;

        $encrypted = '' ;
        $pubKey = file_get_contents($kpath);
        openssl_public_encrypt($key, $encrypted, $pubKey) ;
        $mkey = base64_encode($encrypted);

        $encrypted = '' ;
        $pubKey = file_get_contents($kpath);
        openssl_public_encrypt($iv, $encrypted, $pubKey) ;
        $miv = base64_encode($encrypted);

        $m = [
            'sss' => time() ,
            'data' => $mdata ,
            'key' => $mkey ,
            'iv' => $miv ,
        ] ;

        return $m;
    }

    public function decodeResponse($data){

        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
        $key = $this->key ;
        $iv = $this->iv ;

        mcrypt_generic_init($td, $key, $iv);

        /* 解密数据 */
        $src = base64_decode($data);

        $data = @mdecrypt_generic($td, $src);

        $data = $this->pkcs5_unpad($data) ;


        $ret = json_decode($data, true) ;

        return $ret;
    }

    public function pkcs5_pad ($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    public function pkcs5_unpad($text)
    {
        $pad = ord($text{strlen($text)-1});
        if ($pad > strlen($text)) return false;
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
        return substr($text, 0, -1 * $pad);
    }

}